﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerFrame
{
    public class LengthE_D
    {
        //编码
        public static byte[] LengthEncode(byte[] Model) {

            if (Model == null||Model.Length==0) {
                return null; 
            }

            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);     //BinaryWriter--二进制写入

            bw.Write(Model.Length);

            bw.Write(Model);

            byte[] result = new byte[ms.Length];
            Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length);

            bw.Close();
            ms.Close();

            return result;
        }

        //解码
        public static byte[] LengthDecode(ref List<byte> deModel) {
            if (deModel == null || deModel.Count < 4)   //|| deModel.Count == 0
            {
                return null;
            }
            else {
                MemoryStream ms = new MemoryStream(deModel.ToArray());
                BinaryReader br = new BinaryReader(ms);

                int i = br.ReadInt32();

                //byte[] result = new byte[i];
                //Buffer.BlockCopy(ms.GetBuffer(), 4, result, 0, i);
                if (deModel.Count - 4 < i) {
                    br.Close();
                    ms.Close();
                    return null;
                }
                else
                {
                    //byte[] temp = new byte[deModel.Count - (4 + i)];

                    //Buffer.BlockCopy(deModel.ToArray(), 4 + i, temp, 0, temp.Length);
                    byte[] temp = new byte[i];

                    Buffer.BlockCopy(deModel.ToArray(), 4 , temp, 0, temp.Length);
                    deModel.Clear();
                    deModel.AddRange(temp);

                    br.Close();
                    ms.Close();

                    return temp;
                }


                
            }
            

        }
    }
}
